package com.platform.qujia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.platform.qujia.dao.*;
import com.platform.qujia.param.request.GoToInvoice;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.InvoiceService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Auther: zxy
 * @Date: 2023/8/8 12:35
 * @Description:
 */
@Service("InvoiceService")
@Transactional
public class InvoiceServiceImpl implements InvoiceService {

    @Resource
    private PayOrderMapper payOrderMapper;

    @Resource
    private InvoiceMapper invoiceMapper;

    @Resource
    private PhysicalCardBalanceMapper physicalCardBalanceMapper;

    @Resource
    private FleetCardMapper fleetCardMapper;

    @Resource
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;

    @Resource
    private SuperPayOrderMapper superPayOrderMapper;

    @Override
    public int insertInvoiceInfo(GoToInvoice invoice, PayOrder payOrder) {
        //获取输入的开票金额
        Double invoiceAmount = invoice.getInvoiceAmount();
        BigDecimal invoicebigDecimal = new BigDecimal(String.valueOf(invoiceAmount));
        //订单支付金额
        Double amt = payOrder.getAmt();
        BigDecimal amtbigDecimal = new BigDecimal(String.valueOf(amt));
        //开票金额不能大于支付金额
        if (invoicebigDecimal.compareTo(amtbigDecimal) < 0) {
            //剩余可开票金额
            double balance = amtbigDecimal.subtract(invoicebigDecimal).doubleValue();
            InvoiceInfoVo invoiceInfo = InvoiceInfoVo.builder()
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .businessId(invoice.getBusinessId())
                    .invoiceStatus(2)
                    .invoiceBalance(balance)
                    .build();
            invoiceMapper.insertInvoice(invoiceInfo);
            InvoiceInfoVo invoiceInfoVo = invoiceMapper.selectInvoiceInfoByOrdNo(invoice.getOrderNo());
            //插入开票记录
            InvoiceInfoVo invoiceRecord = InvoiceInfoVo.builder()
                    .invoiceId(invoiceInfoVo.getInvoiceId())
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .businessId(invoice.getBusinessId())
                    .invoiceStatus(invoiceInfoVo.getInvoiceStatus())
                    .invoiceBalance(invoiceInfoVo.getInvoiceBalance())
                    .build();
            return invoiceMapper.insertInvoiceRecord(invoiceRecord);

        } else if (invoicebigDecimal.compareTo(amtbigDecimal) == 0) {
            InvoiceInfoVo invoiceInfo = InvoiceInfoVo.builder()
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .businessId(invoice.getBusinessId())
                    .invoiceBalance(0.00)
                    .invoiceStatus(1)
                    .build();
            invoiceMapper.insertInvoice(invoiceInfo);
            InvoiceInfoVo invoiceInfoVo = invoiceMapper.selectInvoiceInfoByOrdNo(invoice.getOrderNo());
            //插入开票记录
            InvoiceInfoVo invoiceRecord = InvoiceInfoVo.builder()
                    .invoiceId(invoiceInfoVo.getInvoiceId())
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .businessId(invoice.getBusinessId())
                    .invoiceStatus(invoiceInfoVo.getInvoiceStatus())
                    .invoiceBalance(invoiceInfoVo.getInvoiceBalance())
                    .build();
            return invoiceMapper.insertInvoiceRecord(invoiceRecord);
        }
        return 0;
    }
    @Override
    public int insertInvoiceInfo(GoToInvoice invoice, Double amt) {
        //获取输入的开票金额
        Double invoiceAmount = invoice.getInvoiceAmount();
        BigDecimal invoicebigDecimal = new BigDecimal(String.valueOf(invoiceAmount));
        //订单支付金额
        //Double amt = payOrder.getAmt();
        BigDecimal amtbigDecimal = new BigDecimal(String.valueOf(amt));
        //开票金额不能大于支付金额
        if (invoicebigDecimal.compareTo(amtbigDecimal) < 0) {
            //剩余可开票金额
            double balance = amtbigDecimal.subtract(invoicebigDecimal).doubleValue();
            InvoiceInfoVo invoiceInfo = InvoiceInfoVo.builder()
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .businessId(invoice.getBusinessId())
                    .invoiceStatus(2)
                    .invoiceBalance(balance)
                    .businessName(invoice.getBusinessName())
                    .build();

            invoiceMapper.insertInvoice(invoiceInfo);
           // InvoiceInfoVo invoiceInfoVo = invoiceMapper.selectInvoiceInfoByOrdNoAndBusinessName(invoice.getOrderNo(),invoice.getBusinessName());
            //插入开票记录
            InvoiceInfoVo invoiceRecord = InvoiceInfoVo.builder()
                    .invoiceId(invoiceInfo.getInvoiceId())
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .invoiceStatus(invoiceInfo.getInvoiceStatus())
                    .invoiceBalance(invoiceInfo.getInvoiceBalance())
                    .businessName(invoice.getBusinessName())
                    .build();
            int i = invoiceMapper.insertInvoiceRecord(invoiceRecord);
            return i;
        } else if (invoicebigDecimal.compareTo(amtbigDecimal) == 0) {
            InvoiceInfoVo invoiceInfo = InvoiceInfoVo.builder()
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())
                    .invoiceBalance(0.00)
                    .invoiceStatus(1)
                    .businessName(invoice.getBusinessName())
                    .build();
            invoiceMapper.insertInvoice(invoiceInfo);
            //InvoiceInfoVo invoiceInfoVo = invoiceMapper.selectInvoiceInfoByOrdNoAndBusinessName(invoice.getOrderNo(),invoice.getBusinessName());
            //插入开票记录
            InvoiceInfoVo invoiceRecord = InvoiceInfoVo.builder()
                    .invoiceId(invoiceInfo.getInvoiceId())
                    .invoiceAmount(invoiceAmount)
                    .orderNo(invoice.getOrderNo())

                    .invoiceStatus(invoiceInfo.getInvoiceStatus())
                    .invoiceBalance(invoiceInfo.getInvoiceBalance())
                    .businessName(invoice.getBusinessName())
                    .build();
            return invoiceMapper.insertInvoiceRecord(invoiceRecord);
        }
        return 0;
    }

    @Override
    public InvoiceInfoVo selectInvoiceInfoByOrdNo(String orderNo) {
        InvoiceInfoVo invoiceInfoVo = invoiceMapper.selectInvoiceInfoByOrdNo(orderNo);
        if (ObjectUtils.isEmpty(invoiceInfoVo)){
            PayOrder payOrder = payOrderMapper.selectOrderInfoByOrdNo(orderNo);
            if (ObjectUtils.isEmpty(payOrder)){
                try {
                    throw new Exception("没找到改订单信息");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            BigDecimal originalAmt = payOrder.getOriginalAmt();
            if (originalAmt != null) {
                payOrder.setAmt(originalAmt.doubleValue());
                payOrder.setReceivedAmt(originalAmt.doubleValue());
            }
            return InvoiceInfoVo.builder()
                    .invoiceBalance(payOrder.getAmt())
                    .orderNo(payOrder.getOrderNo())
                    .invoiceStatus(0)
                    .build();
        }
        return invoiceInfoVo;
    }
    @Override
    public InvoiceInfoVo selectInvoiceInfoByOrdNoAndBusinessName(String orderNo,String businessName) {
        InvoiceInfoVo invoiceInfoVo = invoiceMapper.selectInvoiceInfoByOrdNoAndBusinessName(orderNo,businessName);
        if (ObjectUtils.isEmpty(invoiceInfoVo)){
            Double amt=0d;
            if(businessName.equals(GoToInvoice.BUSINESSNAME_PAY_ORDER)){
                PayOrder payOrder = payOrderMapper.selectOrderInfoByOrdNo(orderNo);
                if (ObjectUtils.isEmpty(payOrder)){
                    try {
                        throw new Exception("没找到该订单信息");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                BigDecimal originalAmt = payOrder.getOriginalAmt();
                if (originalAmt != null) {
                    payOrder.setAmt(originalAmt.doubleValue());
                    payOrder.setReceivedAmt(originalAmt.doubleValue());
                }
                amt = payOrder.getAmt();
            }
            if(businessName.equals(GoToInvoice.BUSINESSNAME_PHYSICAL_CARD_BALANCE)){
                PhysicalCardBalance physicalCardBalance = physicalCardBalanceMapper.selectByOrderNo(orderNo);
                if (ObjectUtils.isEmpty(physicalCardBalance)){
                    try {
                        throw new Exception("没找到该订单信息");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                amt=physicalCardBalance.getAmount().doubleValue();
            }
            if(businessName.equals(GoToInvoice.BUSINESSNAME_FLEET_CARD_RECHARGE_RECORD)){
                FleetCardRechargeRecord fleetCardRechargeRecord = fleetCardMapper.selectRechargeRecordByRecordId(Long.parseLong(orderNo));
                if (ObjectUtils.isEmpty(fleetCardRechargeRecord)){
                    try {
                        throw new Exception("没找到该订单信息");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                amt = fleetCardRechargeRecord.getRechargeAmount().doubleValue();

            }
            if(businessName.equals(GoToInvoice.BUSINESSNAME_CUSTOMER_CARD_USE_REORD)){
                CustomerCardUseRecord cardUseRecord = customerCardUseRecordMapper.getByOrderNo(orderNo);
                if (ObjectUtils.isEmpty(cardUseRecord)){
                    try {
                        throw new Exception("没找到该订单信息");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                amt = cardUseRecord.getAmt().doubleValue();
            }
            if(businessName.equals(GoToInvoice.BUSINESSNAME_SUPER_PAY_ORDER)){
                SuperPayOrder superPayOrder=new SuperPayOrder();
                superPayOrder.setSuperOrderNo(orderNo);
                List<SuperPayOrder> superPayOrders = superPayOrderMapper.selectSuperPayOrderList(superPayOrder);
                if(superPayOrders.size()>0){
                    superPayOrder= superPayOrders.get(0);
                }else{
                    throw new RuntimeException(new Exception("没找到该订单信息"));
                }
                amt = superPayOrder.getAmt().doubleValue();
            }


            return InvoiceInfoVo.builder()
                    .invoiceBalance(amt)
                    .orderNo(orderNo)
                    .invoiceStatus(0)
                    .businessName(businessName)
                    .build();

        }
        return invoiceInfoVo;
    }

    @Override
    @Transactional
    public int updateInvoiceInfo(InvoiceInfoVo invoiceInfo, GoToInvoice invoice) {
        //旧的开票金额
        BigDecimal oldAmount = convertUtil(invoiceInfo.getInvoiceAmount());
        //新的开票金额
        BigDecimal amount = convertUtil(invoice.getInvoiceAmount());
        //相加
        BigDecimal addInvoiceAmount = oldAmount.add(amount);
        InvoiceInfoVo invoiceInfoVo = new InvoiceInfoVo();
        BeanUtil.copyProperties(invoiceInfo, invoiceInfoVo);
        invoiceInfoVo.setInvoiceAmount(addInvoiceAmount.doubleValue());
        //剩余可开票金额
        BigDecimal balance = convertUtil(invoiceInfo.getInvoiceBalance());
        BigDecimal subtract = balance.subtract(amount);
        invoiceInfoVo.setInvoiceBalance(subtract.doubleValue());
        //判断更改状态
        if (subtract.compareTo(BigDecimal.ZERO) == 0) {
            invoiceInfoVo.setInvoiceStatus(1);
        }
        invoiceMapper.updateInvoiceInfo(invoiceInfoVo);
        //插入开票记录
        InvoiceInfoVo invoiceRecord = InvoiceInfoVo.builder()
                .invoiceId(invoiceInfoVo.getInvoiceId())
                .invoiceAmount(invoice.getInvoiceAmount())
                .orderNo(invoice.getOrderNo())
                .invoiceStatus(invoiceInfoVo.getInvoiceStatus())
                .invoiceBalance(subtract.doubleValue())
                .businessName(invoice.getBusinessName())
                .build();
        return invoiceMapper.insertInvoiceRecord(invoiceRecord);
    }

    @Override
    public List<InvoiceInfoVo> getInvoiceRecords(String orderNo) {
        return invoiceMapper.selectInvoiceRecordsByOrdNo(orderNo);
    }

    @Override
    public List<InvoiceInfoVo> queryByBusinessNameAndId(GoToInvoice invoice) {
        return invoiceMapper.queryByBusinessNameAndId(invoice);
    }





    private BigDecimal convertUtil(Double d) {
        return new BigDecimal(String.valueOf(d));
    }
}
